//
//  AppUI.m
//  mbstore
//
//  Created by huangyi on 14-3-12.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "AppUI.h"
#import "TreeUIM.h"
#import "HomeUI.h"
NSString *const ItemListNotification=@"item-changed";
NSString *const ShoppingListNotification=@"shopping-changed";
NSString *const ChangSelcetType=@"select-chang";
@implementation MainApp

-(instancetype)init{
    self=[super init];
    if (self) {
        self.shoppingList=[NSMutableArray array];
        self.itemList=[NSMutableArray array];
        self.promotionList=[NSMutableArray array];
        self.skuInfoCache=[NSMutableDictionary dictionary];

        NSString *dbfile=[[NSBundle mainBundle] pathForResource:@"media.bundle/mb.db" ofType:nil];
        SQLiteKit *sqlite=[[SQLiteKit alloc] initWithDatabase:dbfile];
        self.sqlite=sqlite;
    }
    return self;
}

+(instancetype)mainApp{
    static MainApp *app=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        app=[[MainApp alloc] init];
    });
    return app;
}

#warning TODO: 商品信息缓存
//添加到购物车后，后台获取商品信息，缓存，用于查询折扣
//sku查询，因为商品请求是添加商品按钮点击后发起的，这里假定在点击购物车列表之前就已经得到了结果，否则查询折扣会得不到商品信息
-(NSDictionary*)requestProduct:(NSString*)skuId{
    NSDictionary *info=self.skuInfoCache[skuId];
    if (!info) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            HTTPClient *client=[AppUI getProduct:skuId];
            if (!client.error) {
                NSDictionary *response=[client.responseData JSONObject];
                NSArray *details=[response valueForKey:@"DetailEntitys"];
                if (![details isEqual:[NSNull null]]&&details.count>0) {
                    NSDictionary *detail=[details firstObject];
                    if (detail) {
                        [self.skuInfoCache setValue:detail forKey:skuId];
                    }
                }
            }
        });
    }
    return info;
}

-(NSArray*)requestPromotion{
    if (self.promotionList.count==0) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            HTTPClient *client=[AppUI getPromotion];
            if (!client.error) {
                NSDictionary *response=[client.responseData JSONObject];
                NSArray *details=[response valueForKey:@"PromotionRuleSelects"];
                if (details.count>0) {
                    [self.promotionList addObjectsFromArray:details];
                }
            }
        });
    }
    return self.promotionList;
}

@end

@interface AppUI ()

@end

@implementation AppUI

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)presentWithNavigationController:(UIViewController*)controller{
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:controller];
    nav.modalPresentationStyle=controller.modalPresentationStyle;
    nav.modalTransitionStyle=controller.modalTransitionStyle;
    nav.navigationBar.translucent=NO;
    if (self.navigationController) {
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }else{
        [self presentViewController:nav animated:YES completion:nil];
    }
}
-(void)AddChildWithNavigationController:(UIView*)controller{
   

  /*  UIViewController *contrl=[self.navigationController.childViewControllers lastObject];
    static TreeUIM *tree=nil;
    static UINavigationController *nav=nil;
    if (tree==nil) {
        tree=[[TreeUIM alloc] init];
        nav=[[UINavigationController alloc] initWithRootViewController:tree];
        [ nav.view.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        //    nav.view.alpha=0.0;
        [nav.view.layer setBorderWidth:1.0f];
    }
    tree.delegate=controller;
//    nav.view.frame=CGRectMake(-self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height);
    nav.view.frame=CGRectOffset(self.view.bounds, -self.view.frame.size.width, 0);
    [contrl addChildViewController:nav];
    [contrl.view addSubview:nav.view];
    [self ShowChildCtr:nav.view];*/
    UIViewController *contrl=[self.navigationController.childViewControllers lastObject];
    static TreeUIM *tree=nil;
    if (tree==nil) {
        tree=[[TreeUIM alloc] init];
        [ tree.view.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        [tree.view.layer setBorderWidth:1.0f];
    }
    tree.delegate=controller;
    tree.view.frame=CGRectOffset(self.view.bounds, -self.view.frame.size.width, 0);
    [contrl addChildViewController:tree];
    [contrl.view addSubview:tree.view];
    [self ShowChildCtr:tree.view];
}

-(void)RemoveFormParent:(CGFloat)time{
     UIViewController *contrl=self.parentViewController;
    float animateTime=0.3;
    if (![contrl isKindOfClass:[HomeUI class]]&&time==0.0f) {
        animateTime=time;
    }
//    if (self.navigationController) {
//         [self HideChildCtr:self.navigationController.view Time:animateTime];
//    }
//    else{
        [self HideChildCtr:self.view Time:animateTime];
//    }
   
}
-(void)ShowChildCtr:(UIView *)view{
    [UIView animateWithDuration:0.3 animations:^{
        view.frame=CGRectOffset(self.view.bounds, 0, 0);

    } completion:^(BOOL finished) {
        
    }];
}
-(void)HideChildCtr:(UIView *)view Time:(float)time{
    [self.navigationController willMoveToParentViewController:nil];
    [UIView animateWithDuration:time animations:^{
         view.frame=CGRectOffset(self.view.bounds, -self.view.frame.size.width, 0);
    } completion:^(BOOL finished) {
        [self.navigationController removeFromParentViewController];
        [view removeFromSuperview];
    }];
    
}

-(MainApp*)app{
   
    return [MainApp mainApp];
}
+ (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
+(NSArray*)getMainTree{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=@"select distinct main_tree from p_tree where 1 order by rowid asc";
    return [sqlite getCol:sql];
}
+(NSArray*)getSubTree:(NSString*)mainTree{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select distinct sub_tree from p_tree where main_tree='%@' order by rowid asc",mainTree];//获取分类（性别）
    return [sqlite getCol:sql];
}
+(NSArray*)getAllSuit{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    //查询不重复的ID
    NSString *sql=[NSString stringWithFormat:@"select distinct item_id from p_suit where 1 order by rowid asc"];//查询所有
    return [sqlite getCol:sql];
}
+(NSArray*)getSuitByScan:(NSString*)scan{
    if (scan.length<6) {
        return [NSArray array];
    }
    //获取前6为
    NSString *itemId=[scan substringToIndex:6];
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select distinct item_id from p_suit where pdts like '%@%%' order by rowid asc",itemId];//扫码检索（货号）
    return [sqlite getCol:sql];
}
+(NSArray*)getSuitByTree:(NSArray*)tree{//获取分类后检索图片（性别，类型，货号）
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSMutableArray *itemList=[NSMutableArray array];
    if (tree.count==1) {
        NSString *mainTree=[tree objectAtIndex:0];
        NSString *sql=[NSString stringWithFormat:@"select distinct item_id from p_tree where main_tree='%@'order by rowid asc",mainTree];
        [itemList addObjectsFromArray:[sqlite getCol:sql]];
    }
    if (tree.count==2) {
        NSString *mainTree=[tree objectAtIndex:0];
        NSString *subTree=[tree objectAtIndex:1];
        NSString *sql=[NSString stringWithFormat:@"select distinct item_id from p_tree where main_tree='%@' and sub_tree='%@' order by rowid asc",mainTree,subTree];
        [itemList addObjectsFromArray:[sqlite getCol:sql]];
    }
    if (itemList.count>0) {
        NSMutableArray *pdts=[NSMutableArray array];
        for (NSString *pdt in itemList) {
            NSString *str=[NSString stringWithFormat:@"'%@'",pdt];
            [pdts addObject:str];
        }
        NSString *pdtList=[pdts componentsJoinedByString:@","];
        NSString *sql=[NSString stringWithFormat:@"select distinct item_id from p_suit where pdts in (%@) order by rowid asc",pdtList];
        return [sqlite getCol:sql];
    }else{
        return [NSMutableArray array];
    }
}
+(NSArray*)getProductByTree:(NSArray*)tree{//检索（性别 ，上装或下装）
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSMutableArray *itemList=[NSMutableArray array];
    NSString *category=[tree objectAtIndex:0];
    if (tree.count==2) {
        NSString *mainTree=[tree objectAtIndex:1];
        NSString *sql=[NSString stringWithFormat:@"select distinct item_id from p_tree where category='%@' and main_tree='%@' order by rowid asc",category,mainTree];
        [itemList addObjectsFromArray:[sqlite getCol:sql]];
    }
    if (tree.count==3) {
        NSString *mainTree=[tree objectAtIndex:1];
        NSString *subTree=[tree objectAtIndex:2];
        NSString *sql=[NSString stringWithFormat:@"select distinct item_id from p_tree where category='%@' and main_tree='%@' and sub_tree='%@' order by rowid asc",category,mainTree,subTree];
        [itemList addObjectsFromArray:[sqlite getCol:sql]];
    }
    if (itemList.count>0) {
        NSMutableArray *pdts=[NSMutableArray array];
        for (NSString *pdt in itemList) {
            NSString *str=[NSString stringWithFormat:@"'%@'",pdt];
            [pdts addObject:str];
        }
        NSString *pdtList=[pdts componentsJoinedByString:@","];
        NSString *sql=[NSString stringWithFormat:@"select distinct sku_id from p_sku where item_id in (%@) group by item_id,color_name order by size_name asc,sku_id asc,rowid asc",pdtList];
        return [sqlite getCol:sql];
    }else{
        return [NSMutableArray array];
    }
}
+(NSDictionary*)getSuitDict:(NSString*)itemId{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select * from p_suit where item_id='%@' order by rowid asc",itemId];
    return [sqlite getRow:sql];
}
+(NSArray*)getProductBySuit:(NSString*)itemId{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select pdts from p_suit where item_id='%@' order by rowid asc",itemId];
    return [sqlite getCol:sql];
}
+(NSDictionary*)getProductDict:(NSString*)skuId{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select p_sku.*,p_pdt.name,p_pdt.price,p_pdt.category from p_sku left join p_pdt on p_sku.item_id=p_pdt.item_id where p_sku.sku_id='%@' order by rowid asc",skuId];
    return [sqlite getRow:sql];
}
+(NSArray*)getProductSku:(NSString*)itemId{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select * from p_sku where item_id='%@' order by sku_id asc,rowid asc",itemId];
    return [sqlite getAll:sql];
}
+(NSDictionary*)getSkuDict:(NSString*)skuId{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select * from p_sku where sku_id='%@' order by rowid asc",skuId];
    return [sqlite getRow:sql];
}
+(NSString*)getSkuId:(NSString*)colorAndSize forItem:(NSString*)itemId{
    if (!itemId) {
        return nil;
    }
    NSArray *array=[colorAndSize componentsSeparatedByString:@";"];
    if (array.count!=2) {
        return nil;
    }
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select sku_id from p_sku where item_id='%@' and color_name='%@' and size_name='%@' order by rowid asc",itemId,array[0],array[1]];
    return [sqlite getCell:sql];
}
+(NSString*)getImageURL:(NSString *)imageName{
    return [imageName urlencode];
}

+(NSArray*)getFirstUpperTree{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select main_tree,sub_tree from p_tree where category='上装' order by rowid asc"];
    NSDictionary *row=[sqlite getRow:sql];
    return @[row[@"main_tree"],row[@"sub_tree"]];
}
+(NSArray*)getFirstLowerTree{
    MainApp *app=[MainApp mainApp];
    SQLiteKit *sqlite=app.sqlite;
    NSString *sql=[NSString stringWithFormat:@"select main_tree,sub_tree from p_tree where category='下装' order by rowid asc"];
    NSDictionary *row=[sqlite getRow:sql];
    return @[row[@"main_tree"],row[@"sub_tree"]];
}


#warning TODO: 获取库存接口
//读取json模版，替换skuId
+(HTTPClient*)getStock:(NSString*)skuId{
    NSDictionary *url_json=[[[@"media.bundle/url.json" resourcePath] readString] JSONObject];
    NSString *urlString=[url_json valueForKey:@"stock"];
    HTTPClient *client=[[HTTPClient alloc] initWithURLString:urlString];
    [client setTimeoutInterval:20];
    NSString *stock=[[@"media.bundle/stock.json" resourcePath] readString];
    stock=[stock stringByReplacingOccurrencesOfString:@"$skuId" withString:skuId];
    NSMutableDictionary *api=[NSMutableDictionary dictionary];
    [api setValue:[stock JSONObject] forKeyPath:@"inData"];
    [client setPostObject:api];
    [client execute];
    NSLog(@"URL: %@\nRequest: %@\nResponse: %@",urlString,[api JSONString],[[client.responseData JSONObject] JSONString]);
    return client;
}
#warning TODO: 获取商品接口
//读取json模版，替换skuId
+(HTTPClient*)getProduct:(NSString*)skuId{
    NSDictionary *url_json=[[[@"media.bundle/url.json" resourcePath] readString] JSONObject];
    NSString *urlString=[url_json valueForKey:@"product"];
    HTTPClient *client=[[HTTPClient alloc] initWithURLString:urlString];
    [client setTimeoutInterval:20];
    NSString *product=[[@"media.bundle/product.json" resourcePath] readString];
    product=[product stringByReplacingOccurrencesOfString:@"$skuId" withString:skuId];
    NSMutableDictionary *api=[NSMutableDictionary dictionary];
    [api setValue:[product JSONObject] forKeyPath:@"inData"];
    [client setPostObject:api];
    [client execute];
    NSLog(@"URL: %@\nRequest: %@\nResponse: %@",urlString,[api JSONString],[[client.responseData JSONObject] JSONString]);
    return client;
}
#warning TODO: 获取折扣接口
//pdtInfo为购物车列表查询缓存的商品信息，构造的数组
//读取json模版，求和RetailPrice $Money=>TotalMoney，计数pdtInfo $Qty=>TotalQty，拼接pdtInfo $Bill=>BillSaleDetails
+(HTTPClient*)getDiscount:(NSArray*)pdtInfo{
    NSDictionary *url_json=[[[@"media.bundle/url.json" resourcePath] readString] JSONObject];
    NSString *urlString=[url_json valueForKey:@"discount"];
    HTTPClient *client=[[HTTPClient alloc] initWithURLString:urlString];
    [client setTimeoutInterval:20];
    NSString *discount=[[@"media.bundle/discount.json" resourcePath] readString];
    NSString *bill=[pdtInfo JSONString];
    discount=[discount stringByReplacingOccurrencesOfString:@"$Bill" withString:bill];
    NSString *qty=[NSString stringWithFormat:@"%@",@(pdtInfo.count)];
    discount=[discount stringByReplacingOccurrencesOfString:@"$Qty" withString:qty];
    double sum=0;
    for (NSDictionary *info in pdtInfo) {
        double price=[info[@"RetailPrice"] doubleValue];
        sum+=price;
    }
    NSString *money=[NSString stringWithFormat:@"%@",@(sum)];
    discount=[discount stringByReplacingOccurrencesOfString:@"$Money" withString:money];
    NSMutableDictionary *api=[NSMutableDictionary dictionary];
    [api setValue:[discount JSONObject] forKeyPath:@"inData"];
    [client setPostObject:api];
    [client execute];
    NSLog(@"URL: %@\nRequest: %@\nResponse: %@",urlString,[api JSONString],[[client.responseData JSONObject] JSONString]);
    return client;
}

#warning TODO: 获取促销策略
+(HTTPClient*)getPromotion{
    NSDictionary *url_json=[[[@"media.bundle/url.json" resourcePath] readString] JSONObject];
    NSString *urlString=[url_json valueForKey:@"discount"];
    HTTPClient *client=[[HTTPClient alloc] initWithURLString:urlString];
    [client setTimeoutInterval:20];
    NSString *product=[[@"media.bundle/promotion.json" resourcePath] readString];
    NSMutableDictionary *api=[NSMutableDictionary dictionary];
    [api setValue:[product JSONObject] forKeyPath:@"inData"];
    [client setPostObject:api];
    [client execute];
    NSLog(@"URL: %@\nRequest: %@\nResponse: %@",urlString,[api JSONString],[[client.responseData JSONObject] JSONString]);
    return client;
}

#warning TODO: 设置促销策略
+(HTTPClient*)setPromotion:(NSArray*)promotions{
    NSDictionary *url_json=[[[@"media.bundle/url.json" resourcePath] readString] JSONObject];
    NSString *urlString=[url_json valueForKey:@"promotion"];
    HTTPClient *client=[[HTTPClient alloc] initWithURLString:urlString];
    [client setTimeoutInterval:20];
    NSString *product=[[@"media.bundle/promotion_apply.json" resourcePath] readString];
    NSString *rules=[promotions JSONString];
    product=[product stringByReplacingOccurrencesOfString:@"$Rules" withString:rules];
    NSMutableDictionary *api=[NSMutableDictionary dictionary];
    [api setValue:[product JSONObject] forKeyPath:@"inData"];
    [client setPostObject:api];
    [client execute];
    NSLog(@"URL: %@\nRequest: %@\nResponse: %@",urlString,[api JSONString],[[client.responseData JSONObject] JSONString]);
    return client;
}

@end
